package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"
)

type UpgradeTerminals struct{}

// Update 更新升级终端信息
func (UpgradeTerminals) Update(
	ctx context.Context,
	query *dal.Query,
	scheduleID, robotID, TerminalType string,
	upgradeVersion string,
) error {
	ut := query.UpgradeTerminals
	res, err := ut.WithContext(ctx).
		Where(ut.ScheduleID.Eq(scheduleID)).
		Where(ut.RobotID.Eq(robotID)).
		Where(ut.TerminalType.Eq(TerminalType)).
		Update(ut.UpgradeVersion, upgradeVersion)
	if res.RowsAffected > 0 {
		return nil
	} else {
		return err
	}
}

// List 获取升级终端的终端列表
func (UpgradeTerminals) List(
	ctx context.Context,
	query *dal.Query,
	scheduleID, robotID, TerminalType string,
	upgradeVersion string,
	upgradeStatus int,
	page, limit int,
) ([]*models.UpgradeTerminals, error) {
	ut := query.UpgradeTerminals
	utx := ut.WithContext(ctx)
	if scheduleID != "" { // 升级计划
		utx = utx.Where(ut.ScheduleID.Eq(scheduleID))
	}
	if robotID != "" { // 终端id
		utx = utx.Where(ut.RobotID.Eq(robotID))
	}
	if TerminalType != "" { // 终端类型
		utx = utx.Where(ut.TerminalType.Eq(TerminalType))
	}
	if upgradeStatus > 0 { // 升级状态
		utx = utx.Where(ut.UpgradeStatus.Eq(4))
	}
	// 返回记录
	return utx.Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Find()
}
